package com.yunhe.webmvc.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/10/30 0030 20:23
 * @Description: 上传图片
 */
@MultipartConfig(maxFileSize = 1024*1024*20)
@WebServlet(name="Storge",urlPatterns = "/upload")
public class Storge extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<String> list = new ArrayList<> ();//存放文件名集合
        Collection<Part> parts = req.getParts ();//获取上传路径的集合
        for (Part part:parts){
            String fileName = part.getSubmittedFileName ();//获取上传文件的原始文件名
            String substring = fileName.substring ( fileName.lastIndexOf ( "." ) );//获取上传文件名后缀
            String newfilename = System.currentTimeMillis () + substring;//时间戳和后缀名组成新的文件名
            File file = new File ( "/var/fs" );
            if (!file.isDirectory ()){
                file.mkdirs ();
            }
            part.write ( file +File.separator+newfilename);//上传的路径
            list.add ( newfilename );
        }
//        返回JSON
        resp.setContentType ( "application/json" );
        PrintWriter writer = resp.getWriter ();
        writer.write ( JSON.toJSONString ( list ) );
        writer.close ();
    }
}
